<?php
/**
 *author:韩帅
 *createtime:2017/6/20 10:58
 *description:
 */
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Card extends Model
{
    /**
     * 定义主键字段
     *
     * @var string
     */
    protected $primaryKey = 'id';

    /**
     * 定义表名，不含前缀
     *
     * @var string
     */
    protected $table      = 'wd_user_card';

    /**
     * 定义拒绝保存的字段
     *
     * @var array
     */
    protected $guarded    = ['id'];

    /**
     * 开启laravel默认的时间记录
     *
     * @var bool
     */
    public $timestamps = true;

    /**
     * 定义启用的状态
     */
    const STATUS_BEGIN = 1;

    /**
     * 定义禁用的状态
     */
    const STATUS_STOP  = 0;

    /**
     * 定义已删除的状态
     */
    const ISDELETE_YES  = 1;

    /**
     * 定义未删除的状态
     */
    const ISDELETE_NO   = 0;

    /**
     * 定义和银行卡类型的关联关系
     */
    public function cardType() {

        return $this->hasOne('App\Models\CardType','id','card_type')->where('status',self::STATUS_BEGIN);
    }

    /**
     * 银行卡列表处理
     */
    public static function cardList($data) {
        $newArr = [];

        foreach ($data as $k => $v) {

            $card_num = mb_substr($v['card_num'],-4);
            $card_num = '****'.' '.'****'.' '.'****'.' '.$card_num;
            $newArr['card_list'][]  = ['id'=> $v['id'],'card_num'=> $card_num,'card_type'=>$v['card_type']['name'],
                                        'card_type_logo'=>$v['card_type']['logo']];
        }
        return $newArr;
    }

    /**
     * [cardList 银行卡号是否正确]
     * luha 算法
     * @return [type]  bool
     */
    public static function check_card($no)
    {
        $return = false;
        $arr_no = str_split($no);

        $last_n = $arr_no[count($arr_no)-1];

        krsort($arr_no);

        $i = 1;
        $total = 0;

        foreach ($arr_no as $n){

            if($i%2==0){

                $ix = $n*2;

                if($ix>=10){

                    $nx = 1 + ($ix % 10);
                    $total += $nx;

                }else{

                    $total += $ix;

                }

            }else{

                $total += $n;

            }

            $i++;
        }

        $total -= $last_n;
        $total *= 9;

        if($last_n == ($total%10)){
            $return = true;
        }

        return $return;
    }
}